package com.spring.beanpostprocessor;

import com.spring.annotation.Value;
import com.spring.util.ClassUtils;

import java.lang.reflect.Field;

public class ValueAnnotationHandler implements BeanPostProcessor {
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) {
		
		Class<?> clazz = bean.getClass();
		Field[] fields = clazz.getDeclaredFields();
		
		// 遍历成员变量，搜索 @Value 注解的
		for (Field field : fields) {
			Value value = field.getAnnotation(Value.class);
			if (value != null) {
				handlerValueAnnotation(field, bean, value);
			}
		}
		return bean;
	}
	
	private void handlerValueAnnotation(Field field, Object bean, Value valueAnnotation) {
		String value = valueAnnotation.value();
		Object val = null;
		String fieldTypeName = field.getType().getName();
		switch (fieldTypeName) {
			case "java.lang.String":
				val = value;
				break;
			case "int":
			case "java.lang.Integer":
				val = Integer.parseInt(value);
				break;
			
			case "long":
			case "java.lang.Long":
				val = Long.parseLong(value);
				break;
			
			case "double":
			case "java.lang.Double":
				val = Double.parseDouble(value);
				break;
			
			case "float":
			case "java.lang.Float":
				val = Float.parseFloat(value);
				break;
			default:
				break;
		}
		if (val == null) {
			return;
		}
		
		ClassUtils.assignValueToField(bean, field, val);
	}
}
